package com.dmall.chapter09.section07;

public class LeetCode980 {
    private int[][] grid;
    private int R, C;
    private int start, end;
    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public int uniquePathsIII(int[][] grid) {
        this.grid = grid;
        this.R = grid.length;
        this.C = grid[0].length;
        int left = R * C;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (grid[i][j] == 1) {
                    this.start = i * C + j;
                    grid[i][j] = 0;
                } else if (grid[i][j] == 2) {
                    this.end = i * C + j;
                    grid[i][j] = 0;
                } else if (grid[i][j] == -1) {
                    left--;
                }
            }
        }
        int visited = 0;
        return dfs(visited, start, left);
    }

    private int dfs(int visited, int v, int left) {

        visited += (1 << v);
        left--;
        if (v == end && left == 0) {
            visited -= (1 << v);
            return 1;
        }
        int x = v / C, y = v % C;
        int res = 0;
        for (int i = 0; i < dirs.length; i++) {
            int nextx = x + dirs[i][0], nexty = y + dirs[i][1];
            int next = nextx * C + nexty;
            if (inArea(nextx, nexty) && (visited & (1 << next)) == 0 && grid[nextx][nexty] == 0) {
                res += dfs(visited, next, left);
            }
        }

        visited -= (1 << v);
        return res;
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        int[][] grid = {{1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 2, -1}};
        LeetCode980 leetCode980 = new LeetCode980();
        int count = leetCode980.uniquePathsIII(grid);
        System.out.println(count);
    }
}
